package com.cqrt.aop;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.cqrt.constant.RTErrorCodeEnum;
import com.cqrt.mapper.RTOutRuleMapper;
import com.cqrt.mapper.RTProjectMapper;
import com.cqrt.mapper.RTTaskMapper;
import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSONObject;
import com.cqrt.entity.DeliverableLinkDO;
import com.cqrt.mapper.DeliverableLinkMapper;
import com.cqrt.mapper.RtWorkItemMapper;
import com.cqrt.service.RTTaskService;
import com.github.pagehelper.PageInfo;
import com.hustcad.plm.pdm.core.response.PageDTO;
import com.hustcad.plm.pdm.core.response.TyppmResponseResult;
import com.hustcad.plm.pdm.preview.enums.PreviewErrorCodeEnum;
import com.hustcad.plm.rpm.model.dto.job.JobStatusUpdateDTO;
import com.hustcad.plm.rpm.model.dto.job.TyppmJobDTO;
import com.hustcad.plm.rpm.model.dto.remote.RemoteObjDTO;
import com.hustcad.plm.rpm.model.vo.outrule.OutRuleQC;
import com.hustcad.plm.rpm.service.remoterequest.ThirdRemoteRequestService;
import com.hustcad.plm.rpm.util.request.RequestBase;
import com.ty.basic.constant.TableTypeConstrant;
import com.ty.basic.entity.attribute.StringValueDO;
import com.ty.basic.service.snow.SnowflakeIdComponent;
import com.ty.basic.session.TyAccountContext;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.transaction.SystemException;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Aspect
@Component
@Slf4j
public class ExecutorJobAop {

    @Resource
    RtWorkItemMapper rtWorkItemMapper;
    @Resource
    RTTaskMapper rtTaskMapper;
    @Resource
    RTProjectMapper rtProjectMapper;
    @Resource
    private ThirdRemoteRequestService thirdRemoteRequestService;
    @Resource
    private DeliverableLinkMapper deliverableLinkMapper;

    @Resource
    private OutRuleAop outRuleAop;

    @Resource
    private SnowflakeIdComponent snowflakeIdComponent;

    @Resource
    private RTOutRuleMapper rtOutRuleMapper;
    @Resource
    private RTTaskService rtTaskService;

    @Around(value = "execution(* com.hustcad.plm.rpm.controller.job.JobController.queryExecutorJobByCurrentUser(..))")
    public Object queryExecutorJobByCurrentUser(ProceedingJoinPoint joinPoint) throws Throwable {
        String state=(String) joinPoint.getArgs()[0];
        Integer pageNum=(Integer) joinPoint.getArgs()[1];
        Integer pageSize=(Integer) joinPoint.getArgs()[2];
        BigInteger excutorOid = TyAccountContext.getUser().getOid();

        TyppmResponseResult<PageInfo<TyppmJobDTO>> proceed = (TyppmResponseResult<PageInfo<TyppmJobDTO>>)joinPoint.proceed();
        if (true){
            return proceed;
        }
        List<TyppmJobDTO> list =proceed.getData().getList();
        for (TyppmJobDTO jobDTO : list) {
            //延期分类
            jobDTO.setExtensionClassification(rtWorkItemMapper.queryExtendedAttributes(jobDTO.getOid(),"PostponedClassification"));
            //挽回计划
            jobDTO.setRecoveryPlan(rtWorkItemMapper.queryExtendedAttributes(jobDTO.getOid(),"RecoveryPlan"));
            //责任人
            jobDTO.setPersonCharge(rtWorkItemMapper.queryExtendedAttributes(jobDTO.getOid(),"PersonCharge"));
        }
        for (int i = 0; i < list.size(); i++) {
            TyppmJobDTO jobDTO = list.get(i);
            String jobId = jobDTO.getOid().toString();
            //通过任务ID查询活动 ID
            BigInteger activityIdBigInteger = rtTaskMapper.selectActivityIdById(jobId);
            String activityId = "";
            if(activityIdBigInteger!=null){
                activityId = activityIdBigInteger.toString();
            }
            //通过活动ID查询前置任务的OID
            List<BigInteger> predecessorTaskOidBigIntegers = rtTaskMapper.selectBOidByAOid(activityId);
            //如果存在前置任务，且前置任务状态不是已完成，抛出异常
            if (CollUtil.isNotEmpty(predecessorTaskOidBigIntegers)) {
                for (BigInteger predecessorTaskOidBigInteger : predecessorTaskOidBigIntegers) {
                    String predecessorTaskOid = predecessorTaskOidBigInteger.toString();
                    String isComplete = rtTaskMapper.selectStateByActivityId(predecessorTaskOid);
                    if (!"已完成".equals(isComplete)) {
                        //waitList.add(jobDTO);
                        list.remove(i);
                    }
                }
            }
            if(jobDTO.getProjectDevelopmentOrder()==null){
                String pjname = rtProjectMapper.selectProjectNameByProjectOid(jobDTO.getProjectID());
                Map<String, String> developmentOrder = rtProjectMapper.selectDevelopmentOrderByProjectName(pjname);
                if (CollUtil.isNotEmpty(developmentOrder)){
                    jobDTO.setProjectDevelopmentOrder(developmentOrder.get("PROJECT_CODE"));
                }
            }

            if (jobDTO.getJobNamePath()==null||jobDTO.getJobNamePath().equals("")){
                String pjname = rtProjectMapper.selectProjectNameByProjectOid(jobDTO.getProjectID());
                jobDTO.setJobNamePath(pjname);
            }

        }

        return proceed;

    }
    //查询提交任务的前置任务是否完成
    @Around(value = "execution(* com.hustcad.plm.rpm.service.impl.job.TyppmJobServiceImpl.setSubmitState(..))")
    public Object checkPredecessorTaskIsComplete(ProceedingJoinPoint joinPoint) throws Throwable {
         //获取jobId
        JobStatusUpdateDTO jobStatusUpdateDTO = (JobStatusUpdateDTO)joinPoint.getArgs()[0];
        String changeState = (String)joinPoint.getArgs()[1];

        String jobId = jobStatusUpdateDTO.getJobId();

        //通过任务ID查询活动 ID
        BigInteger activityIdBigInteger = rtTaskMapper.selectActivityIdById(jobId);
        String activityId = "";
        if(activityIdBigInteger!=null){
            activityId = activityIdBigInteger.toString();
        }
        //通过活动ID查询前置任务的OID
        List<BigInteger> predecessorTaskOidBigIntegers = rtTaskMapper.selectBOidByAOid(activityId);
        //如果存在前置任务，且前置任务状态不是已完成，抛出异常
        if (CollUtil.isNotEmpty(predecessorTaskOidBigIntegers)) {
            for (BigInteger predecessorTaskOidBigInteger : predecessorTaskOidBigIntegers) {
                String predecessorTaskOid = predecessorTaskOidBigInteger.toString();
                String isComplete = rtTaskMapper.selectStateByActivityId(predecessorTaskOid);
                if (!"已完成".equals(isComplete)) {
                    throw RTErrorCodeEnum.PRE_TASK_ERROR.getException("前置任务未完成");
                }
            }
        }
        //检查风险单是否关闭
//        checkRiskFormIfCompleted(jobId);
        //刷新状态
        if (changeState.equals("已提交")){
            List<StringValueDO> stringValueDOList = new ArrayList<>();
            BigInteger oid = snowflakeIdComponent.getInstance().nextId();

            StringValueDO stringValueDO = new StringValueDO();
            stringValueDO.setObjbaseoid(new BigInteger(jobId));
            stringValueDO.setObjbaseotype("ty.projectmng.job.CTyJob");
            BigInteger throughStatus = rtOutRuleMapper.selectOidByDisplayName("通过状态");
            stringValueDO.setAttrdefoid(throughStatus);
            stringValueDO.setAttrdefotype("ty.inteplm.attribute.CTyStringDef");
            stringValueDO.setCreatestamp(new Date());
            stringValueDO.setUpdatestamp(new Date());
            stringValueDO.setModifystamp(new Date());
            stringValueDO.setRefobjbaseotype("ty.zddw.kernel.CTyReferenceBase");
            stringValueDO.setOid(oid);
            stringValueDO.setValue("条件通过");
            stringValueDO.setValuex("条件通过");
            stringValueDOList.add(stringValueDO);
            outRuleAop.updateJobThroughStatus(stringValueDOList,jobId);
        }

        return joinPoint.proceed();
    }

    /**
     * 检查风险单是否关闭
     */
    private void checkRiskFormIfCompleted(String jobId) {
        List<RemoteObjDTO> remoteObjDTOList = this.thirdRemoteRequestService.queryDeliverableByParent(jobId,TableTypeConstrant.TY_JOB_OTYPE, "IN", "");

        List<RemoteObjDTO> data = remoteObjDTOList.stream()
                .filter(item -> "Risk".equals(item.getClassName()))
                .filter(item -> !"通过".equals(item.getValidStatus()) && !"条件通过".equals(item.getValidStatus()))
                .collect(Collectors.toList());
        if(CollUtil.isNotEmpty(data)){
            throw RTErrorCodeEnum.UPDATA_PROJECT_MANAGER_ERROR.getException("风险单未关闭,任务不能提交");
        }
    }


    @Around(value = "execution(* com.hustcad.plm.rpm.service.remoterequest.ThirdRemoteRequestService.queryDeliverableByParent(..))")
    public Object addDeliverableAop(ProceedingJoinPoint joinPoint) throws Throwable {
        Object[] args = joinPoint.getArgs();
        String jobId = (String)args[0];
        List<RemoteObjDTO> proceed = (List<RemoteObjDTO>) joinPoint.proceed();
        for (RemoteObjDTO remoteObjDTO : proceed) {
            String extPros = remoteObjDTO.getExtPros();
            JSONObject prosData = JSONObject.parseObject(extPros);
            String objOid = prosData.getString("masteredoid");
            DeliverableLinkDO deliverableLinkDO = new DeliverableLinkDO();
            deliverableLinkDO.setJobOid(jobId);
            deliverableLinkDO.setLinkMasteredOid(objOid);
            List<DeliverableLinkDO> select = deliverableLinkMapper.select(deliverableLinkDO);
            if(CollUtil.isNotEmpty(select)){
                remoteObjDTO.setFrontStatus(true);
                remoteObjDTO.setFrontStatusCN("是");
            }
        }
        return proceed;
    }






}
